import 'package:common_utils/common_utils.dart';

import '../model/user_info_model.dart';
import '../utils/cj_hive.dart';

enum UserHiveKeys { selfUserInfo, token, imToken, roleType }

class UserInfoManager {
  static final UserInfoManager _instants = UserInfoManager();

  //获取当前实例
  static UserInfoManager get shared => _instants;

  UserInfoModel? _selfUserInfo;

  // 是否登录
  bool isLogin() => (token().isNotEmpty);

  UserInfoManager() {
    // if (TextUtil.isEmpty(token()) && info() != null) {
    //   //没有token有用户信息，进行清除操作
    //   _clearHiveInfo();
    // }
  }

  //退出登录
  loginOut() {
    _clearHiveInfo();

    // CJEventBus.fire(CJEventName.LOGIN_STATE_EXIT);
  }

  //登录成功
  loginSucc(UserInfoModel data) {
    saveUserInfo(data);
    // CJEventBus.fire(CJEventName.LOGIN_STATE_SUCC);
  }
}

// 获取用户数据的方法
extension UserStore on UserInfoManager {
  //获取model
  UserInfoModel? info() {
    if (_selfUserInfo == null) {
      if (!TextUtil.isEmpty(token())) {
        var infoJson = _getHiveInfo(UserHiveKeys.selfUserInfo);
        if (infoJson != null) {
          try {
            _selfUserInfo = UserInfoModel.fromJson(infoJson);
          } catch (e) {}
        }
      }
    }
    return _selfUserInfo;
  }

  //获取token
  String token() => _getHiveInfo(UserHiveKeys.token, defaultValue: "");

  String imtToken() => _getHiveInfo(UserHiveKeys.imToken, defaultValue: "");

  String roleType() =>
      _getHiveInfo(UserHiveKeys.roleType, defaultValue: "agent");

//储存model
  Future<void>? saveUserInfo(UserInfoModel model) {
    _selfUserInfo = model;
    saveToken(model.token);
    saveImToken(model.imToken);
    saveRoleType(model.userInfo?.roleKey ?? "agent");
    return _saveHiveInfo(UserHiveKeys.selfUserInfo, model.toJson());
  }

  //储存token
  Future<void>? saveImToken(String token) =>
      _saveHiveInfo(UserHiveKeys.imToken, token);

  //储存角色
  Future<void>? saveRoleType(String role) =>
      _saveHiveInfo(UserHiveKeys.roleType, role);

//储存token
  Future<void>? saveToken(String token) =>
      _saveHiveInfo(UserHiveKeys.token, token);
}

//对hive的 操作--start
extension HiveOpt on UserInfoManager {
  //获取存储的key
  _getKey(UserHiveKeys key) => key.toString();

  _getHiveInfo(UserHiveKeys key, {dynamic defaultValue}) {
    return CJHive.shared.get(_getKey(key), defaultValue: defaultValue);
  }

  Future<void>? _saveHiveInfo(UserHiveKeys key, dynamic value) {
    if (value == null) {
      return CJHive.shared.delete(_getKey(key));
    } else {
      return CJHive.shared.put(_getKey(key), value);
    }
  }

  _clearHiveInfo() {
    CJHive.shared.delete(_getKey(UserHiveKeys.selfUserInfo));
    CJHive.shared.delete(_getKey(UserHiveKeys.token));
  }
}
